/**   
* @{#} FuncNode.java Create on 2013-8-12 上午8:28:30   
*   
* Copyright (c) 2012 by Baidu.   
*/
package objtable.engine.xmlnode;

import java.lang.reflect.Constructor;
import java.util.ArrayList;

import objtable.core.TableCenter;
import objtable.engine.ExeNode;
import objtable.engine.XmlEngine;
import objtable.engine.xmlnode.gen.Dtype;
import objtable.engine.xmlnode.gen.Func;
import objtable.engine.xmlnode.gen.Param;
import objtable.port.DbPort;

/**   
* @author <a href="mailto:zhangbo07@baidu.com">zhangbo07</a>  
* @version 1.0   
*/
public class FuncNode extends ExeNode {
	private Func func;

	public Func getFunc() {
		return func;
	}

	public void setFunc(Func func) {
		this.func = func;
	}

	@Override
	public void exeNode() {
		try {
			Object o;
			if (func.getParam().size() > 0) {
				TypeObjs to = getTypeObjs();
				Constructor<?> c = Class.forName(func.getClazz())
						.getConstructor(to.cls);
				o = c.newInstance(to.obj);
			} else {
				o = Class.forName(func.getClazz()).newInstance();
			}

			TableCenter.regComputeFunc(func.getFuncname(), o);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private TypeObjs getTypeObjs() {
		ArrayList<Class> cls = new ArrayList<Class>();
		ArrayList obj = new ArrayList();
		for (Param pn : func.getParam()) {
			//目前只实现了dbport
			if (pn.getType() == Dtype.DBPORT) {
				cls.add(DbPort.class);
				obj.add(XmlEngine.getObjById(pn.getValue()));
			}
		}
		Class[] cs = new Class[cls.size()];
		cs = cls.toArray(cs);
		Object[] obs = new Object[cls.size()];
		obs = obj.toArray(obs);

		TypeObjs result = new TypeObjs();
		result.cls = cs;
		result.obj = obs;

		return result;
	}

	class TypeObjs {
		Class<?>[] cls;
		Object[] obj;
	}

}
